package com.yunduansing.demo.web.auth;

import com.yunduansing.demo.exception.MyException;
import com.yunduansing.demo.model.account.LoginResultModel;
import com.yunduansing.demo.model.common.CacheKeyPrefix;
import com.yunduansing.demo.model.common.ResponseModel;
import com.yunduansing.demo.service.JwtService;
import com.yunduansing.demo.service.impl.AuthUserService;
import com.yunduansing.demo.web.BaseController;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "授权相关")
@RestController
public class AuthController extends BaseController {
    @Autowired
    private JwtService jwtService;
    @Autowired
    private AuthUserService authUserService;
    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation("刷新token")
    @PostMapping("/auth/token/refresh")
    public ResponseModel<LoginResultModel> refreshToken(@RequestParam String token) throws MyException {
        var passport=getPassport();
        var validateResult=jwtService.validateToken(passport.getUsername(),token, true);
        if(!validateResult){
            return convertToResponseModel(false, "Refresh token验证失败。");
        }
        //删除原来的token
        var userdetails=authUserService.getUserLoginInfo(passport.getUsername());
        authUserService.deleteUserLoginInfo(passport.getUsername());
        var newToken=authUserService.saveUserLoginInfo(new User(passport.getUsername(),"",userdetails.getAuthorities()));
        var result=new LoginResultModel();
        result.setToken(newToken);
        result.setRefreshToken(redisTemplate.opsForValue().get(CacheKeyPrefix.LOGIN_USER_TOKEN+"refresh:"+passport.getUsername()).toString());
        return ok(result);
    }
}
